import { ChatBubbleOvalLeftEllipsisIcon } from '@heroicons/react/24/outline'
import { ChatBubbleOvalLeftEllipsisIcon as ChatBubbleOvalLeftEllipsisSolidIcon } from '@heroicons/react/24/solid'
import { Dropdown, type MenuProps, Space } from 'antd'
import classNames from 'classnames'
import React, { useState } from 'react'
import { LcSessionStorage } from '@/app/components/bridge/storage'
import { deleteConversation } from '@/service'
import type { ConversationItem } from '@/types/app'
import styles from '@/app/components/base/markdown/render-widgets/list-item/style/index.module.css'
import { IconMore } from '@/app/components/base/markdown/render-widgets/icons'

type ConversationItemViewProps = {
  data: ConversationItem
  isCurrent: boolean
  onCurrentIdChange: (id: string) => void
  onRemove?: (id: string) => void
}

export default ({ data: item, isCurrent, onCurrentIdChange, onRemove }: ConversationItemViewProps) => {
  const ItemIcon
    = isCurrent ? ChatBubbleOvalLeftEllipsisSolidIcon : ChatBubbleOvalLeftEllipsisIcon
  const deleteCon = async () => {
    try {
      await deleteConversation(item.id)
      await LcSessionStorage.getInstance().deleteConversation(item.id)
      onRemove?.(item.id)
    }
    catch (e) {
      console.error(e)
    }
  }
  const handleClick: MenuProps['onClick'] = async (item) => {
    item.domEvent.stopPropagation()
    switch (item.key) {
      case 'DELETE':
        await deleteCon()
        break
    }
  }
  const items: MenuProps['items'] = [
    {
      key: 'DELETE',
      label: <span>删除</span>,
    },
  ]
  const [isMenuOpen, setIsMenuOpen] = useState(false)
  return (
    <div
      onClick={() => onCurrentIdChange(item.id)}
      key={item.id}
      className={classNames(
        'group',
        'justify-between',
        isCurrent
          ? 'bg-primary-50 text-primary-600'
          : 'text-gray-700 hover:bg-gray-100 hover:text-gray-700',
        'group flex items-center rounded-md px-2 py-2 text-sm font-medium cursor-pointer',
      )}
    >
      <span className="flex items-center">
        <ItemIcon
          className={classNames(
            isCurrent
              ? 'text-primary-600'
              : 'text-gray-400 group-hover:text-gray-500',
            'mr-3 h-5 w-5 flex-shrink-0',
          )}
          aria-hidden="true"
        />
        {item.name}
      </span>
      {item.id === '-1'
        ? null
        : <Dropdown menu={{
          items,
          onClick: handleClick,
        }}
        onOpenChange={(open) => {
          setIsMenuOpen(open)
        }}
        >
          <a className={classNames('ml-4 invisible group-hover:visible', {
            [styles.vs_block]: isMenuOpen,
          })} onClick={(e) => {
            e.preventDefault()
            e.stopPropagation()
          }}>
            <Space>
              <span className={styles.icon}><IconMore/></span>
            </Space>
          </a>
        </Dropdown>}
    </div>
  )
}
